﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AuthoSYS.EF;

namespace AuthoSYS.Web.Controllers
{
    public class PermissionController : Controller
    {
        private AuthoDBEntities db = new AuthoDBEntities();

        //
        // GET: /Permission/

        public ActionResult Index(string moduleId)
        {
            var permissions = db.Permissions.Include("Module").Where(p => p.ModuleId == moduleId);
            ViewBag.ModuleId = moduleId;
            return View(permissions.ToList());
        }

        //
        // GET: /Permission/Details/5

        public ActionResult Details(string id = null)
        {
            Permission permission = db.Permissions.Single(p => p.Id == id);
            if (permission == null)
            {
                return HttpNotFound();
            }
            return View(permission);
        }

        //
        // GET: /Permission/Create

        public ActionResult Create(string moduleId)
        {
            ViewBag.ModuleId = new SelectList(db.Modules, "Id", "ModuleName", moduleId);
            var modules = db.Modules.Where(m => m.Id == moduleId);
            int? minValue = 0;

            if (modules.Count() > 0)
            {
                minValue = db.OptionalValues.Where(o => o.AppId == modules.FirstOrDefault().AppId).Min(v => v.OptValue);
            }

            if (minValue == null || minValue <= 0)
            {
                minValue = db.Permissions.Where(p => p.Module.AppId == modules.FirstOrDefault().AppId).Max(p => (int?)p.PermissionValue);

                if (minValue == null || minValue <= 0)
                {
                    minValue = 1;
                }
                else
                {
                    minValue++;
                }
            }

            Permission model = new Permission { Id = Guid.NewGuid().ToString(), PermissionValue = (int)minValue };
            return View(model);
        }

        //
        // POST: /Permission/Create

        [HttpPost]
        public ActionResult Create(Permission permission)
        {
            if (ModelState.IsValid)
            {
                permission.Id = Guid.NewGuid().ToString();
                permission.CreatedOn = DateTime.Now;
                permission.ModifiedOn = DateTime.Now;
                permission.CreatedBy = string.Empty;
                permission.ModifiedBy = string.Empty;

                db.Permissions.AddObject(permission);

                var optValue = db.OptionalValues.Where(v => v.OptValue == permission.PermissionValue && v.AppId == permission.Module.AppId);

                if (optValue.Count() > 0)
                {
                    db.OptionalValues.DeleteObject(optValue.Single());
                }

                db.SaveChanges();
                return RedirectToAction("Index", new { moduleId = permission.ModuleId });
            }

            ViewBag.ModuleId = new SelectList(db.Modules, "Id", "ModuleName", permission.ModuleId);

            return View(permission);
        }

        //
        // GET: /Permission/Edit/5

        public ActionResult Edit(string id = null)
        {
            Permission permission = db.Permissions.Single(p => p.Id == id);
            if (permission == null)
            {
                return HttpNotFound();
            }
            ViewBag.ModuleId = new SelectList(db.Modules, "Id", "ModuleName", permission.ModuleId);
            return View(permission);
        }

        //
        // POST: /Permission/Edit/5
        [HttpPost]
        public ActionResult Edit(Permission permission)
        {
            if (ModelState.IsValid)
            {
                db.Permissions.Attach(permission);
                db.ObjectStateManager.ChangeObjectState(permission, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index", new { moduleId = permission.ModuleId });
            }
            ViewBag.ModuleId = new SelectList(db.Modules, "Id", "ModuleName", permission.ModuleId);
            return View(permission);
        }

        //
        // GET: /Permission/Delete/5
        public ActionResult Delete(string id = null)
        {
            Permission permission = db.Permissions.Single(p => p.Id == id);
            if (permission == null)
            {
                return HttpNotFound();
            }
            return View(permission);
        }

        //
        // POST: /Permission/Delete/5
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {
            Permission permission = db.Permissions.Single(p => p.Id == id);
            OptionalValue optValue = new OptionalValue { Id = Guid.NewGuid().ToString(), AppId = permission.Module.AppId, OptValue = permission.PermissionValue };
            db.OptionalValues.AddObject(optValue);
            db.Permissions.DeleteObject(permission);
            db.SaveChanges();
            return RedirectToAction("Index", new { moduleId = permission.ModuleId });
        }

        public ActionResult GetPermissionsByAppId(string appId, string selectedPermissions)
        {


            var models = db.Permissions.Where(p => p.Module.AppId == appId);

            if (!string.IsNullOrEmpty(selectedPermissions))
            {
                var selected = selectedPermissions.Split(',').ToList();
                foreach (var item in models)
                {
                    item.IsSelected = selected.Contains(item.PermissionValue.ToString());
                }
            }

            return PartialView("_PermissionsByAppIdPartialView", models);
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}